package com.example.administrator.appstpremvpdemo.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.appstpremvpdemo.R;
import com.example.administrator.appstpremvpdemo.common.Constances;
import com.example.administrator.appstpremvpdemo.model.entity.Datebean;
import com.example.administrator.appstpremvpdemo.contract.AppListContract;
import com.example.administrator.appstpremvpdemo.model.entity.ValueBean;
import com.example.administrator.appstpremvpdemo.presenter.TaskListPresenter;
import com.example.administrator.appstpremvpdemo.service.DownloadService;
import com.example.administrator.appstpremvpdemo.util.TextFormaterUtils;
import com.example.administrator.appstpremvpdemo.wegit.DownLoadButton;
import com.lsh.XXRecyclerview.CommonRecyclerAdapter;
import com.lsh.XXRecyclerview.CommonViewHolder;
import com.lsh.XXRecyclerview.XXRecycleView;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by Administrator on 2017/12/1.
 */

public class TasklistActivity extends Activity implements AppListContract.View<Datebean> {

    private static final String TGA = "TOUCH";
    public AppListContract.Presenter<Datebean> mPresenter;
    public XXRecycleView mRecyclerview;
    int pageIndex = 1;
    private TextView mNext;
    List<ValueBean> mdata = new ArrayList<>();
    private CommonRecyclerAdapter<ValueBean> mAdapter;
    private RxPermissions mRxPermissions;
    private AppListContract.Presenter<Datebean> mMPresenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mMPresenter = getPresenter();
        if (mPresenter == null) {
            throw new RuntimeException("presenter can not be null");
        }
        mPresenter.start();
    }

    public void initView() {
        mRecyclerview = ((XXRecycleView) findViewById(R.id.recyclerview));
        mNext = ((TextView) findViewById(R.id.next));
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CommonRecyclerAdapter<ValueBean>(this, mdata, R.layout.list_item) {

            @Override
            public void convert(final CommonViewHolder holder, ValueBean item, int position,boolean b) {
                holder.setText(R.id.title, item.getTitle());
                holder.setText(R.id.type, item.getCategory());
                holder.setText(R.id.size, TextFormaterUtils.getDataSize(item.getSize()) + "");
                holder.setText(R.id.score, "评分" + item.getRate() + "");
                holder.setText(R.id.downloadCount, "下载量" + item.getDownloadCount() + "");
                //holder.setBackgroundImage(TasklistActivity.this, R.id.icon, item.getIcon());
                Glide.with(TasklistActivity.this).load(item.getIcon()).into(((ImageView) holder.getView(R.id.icon)));
                DownLoadButton view = (DownLoadButton) holder.getView(R.id.downloadbtn);
                view.setProgress(item.getProgress());
                if (TextUtils.isEmpty(item.getStatus())) {
                    view.setTextview(Constances.DOWNLOAD_NONAL);
                } else {
                    view.setTextview(item.getStatus());
                }
                view.setOnTouchListener(mListener);
                view.setTag(R.id.tag_first, item);
                view.setTag(R.id.tag_three, position);
            }
        };
        mRecyclerview.setAdapter(mAdapter);
        //绑定Service
        Intent intent = new Intent(this, DownloadService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        mRxPermissions = new RxPermissions(this);
        mRecyclerview.setLoadMoreEnabled(true);
        mRecyclerview.setOnLoadMoreListener(new XXRecycleView.OnLoadMoreListener() {
            @Override
            public void onLoad() {
                mPresenter.getNextPageData();
                mRecyclerview.stopLoad();
            }

            @Override
            public void loadEnd() {

            }
        });
    }

    /**
     * 对按钮进行OnTouch的ACTION_DOWN事件进行点击逻辑
     * 由于notifyDataSetChanged方法调用过程中会导致点击失效，但是down事件一定会执行
     */
    private View.OnTouchListener mListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.e(TGA, "Item_ACTION_DOWN");
                ValueBean valueBean = (ValueBean) v.getTag(R.id.tag_first);
                int position = (int) v.getTag(R.id.tag_three);
                if (Constances.DOWNLOAD_ING.equals(valueBean.getStatus())) {
                    mDownloadService.cancelWhatrequest(valueBean.getApk());
                } else {
                    startDownload(valueBean, position);
                }
                mDownloadService.setOnProgressListener(new DownloadService.OnProgressListener() {
                    @Override
                    public void onprogress(int what, int progress) {
                        mAdapter.getDatas().get(what).setProgress(progress);
                        mAdapter.notifyDataSetChanged();
                    }
                });
                mDownloadService.setOnStatusChangeListener(new DownloadService.onStatusChangeListener() {
                    @Override
                    public void onStatusChange(int what, String status) {
                        mAdapter.getDatas().get(what).setStatus(status);
                        mAdapter.notifyDataSetChanged();
                    }
                });

                break;

            }
            return false;
        }
    };


    @Override
    public void setPresenter(AppListContract.Presenter<Datebean> presenter) {
        this.mPresenter = presenter;
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
        mPresenter.destroy();
    }

    @Override
    public void showApplist(Datebean data) {
        mAdapter.addAll(data.getValue());
    }

    @Override
    public void showNoMoreDataTips() {
        Toast.makeText(this, "没有更多数据", Toast.LENGTH_SHORT).show();
        mRecyclerview.setLoadMoreEnabled(false);
    }

    @Override
    public void showloaderrotips(String erromsg) {
        Toast.makeText(this, erromsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoadingTip() {

    }

    public void startDownload(final ValueBean datebean, final int index) {
        mRxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    mDownloadService.startDownLoad(datebean, index);
                }
            }
        });
    }

    private DownloadService mDownloadService;

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.w("TasklistActivity", "断开链接");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个mDownloadService对象
            mDownloadService = ((DownloadService.DownloadBinder) service).getService();
        }
    };

    public AppListContract.Presenter getPresenter() {
        AppListContract.Presenter<Datebean> presenter = new TaskListPresenter(this, Constances.URL_LIST);
        HashMap<String, String> parms = new HashMap<>();
        parms.put("pageIndex", pageIndex + "");
        presenter.setParms(parms);
        return presenter;
    }
}
